package com.example.Utility;

import com.example.entity.OrderMessage;
import lombok.extern.slf4j.Slf4j;
import reactor.util.annotation.Nullable;

import java.math.BigDecimal;
import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 公共工具
 *
 * @author Super
 */
@Slf4j
public class publicUtils {
    private static final String DATE_FORMAT = "yyyy%sMM%sdd";


    private static final GeneratedSnowFlake snowFlake = new GeneratedSnowFlake(1, 1, 1);

    /**
     * 获取商品总价
     */
    public static BigDecimal getCommodityListAmount(List<OrderMessage> orderMessages) {
        BigDecimal amount = null;
        if (orderMessages != null && !orderMessages.isEmpty()) {
            amount = BigDecimal.ZERO;
            for (OrderMessage orderMessage : orderMessages) {
                BigDecimal unitPrice = orderMessage.getUnitPrice();
                if (unitPrice != null && orderMessage.getOrderAmount() != null) {
                    if (amount == null) {
                        amount = BigDecimal.ZERO;
                    }
                    amount = amount.add(unitPrice.multiply(BigDecimal.valueOf(orderMessage.getOrderAmount())));
                }
            }
        }
        return amount;
    }

    /**
     * 获取当前时间
     *
     * @param layout
     * @return
     * @throws Exception
     */
    public static String getTimes(String layout) {
        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(String.format(DATE_FORMAT, layout, layout));
        String str = null;
        try {
            str = formatter.format(currentDate);
        } catch (DateTimeException e) {
            e.printStackTrace();
        }
        return str;
    }

    /**
     * 生成订单号
     * String suffix 后缀
     *
     * @return String
     */
    public static String generateOrderNumber(@Nullable String suffix) {
        if (objIsNull.isNull(suffix)) {
            log.error("order suffix is null");
            throw new RuntimeException("order suffix is null");

        }
        return String.valueOf(snowFlake.nextId()).substring(0, 12) + suffix;
    }
}
